package com.app.store.dto;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.dd.plist.*;
import org.apkinfo.api.util.AXmlResourceParser;
import org.apkinfo.api.util.XmlPullParser;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * Created by song on 2018/1/2.
 */
public class AppUtil {
    /**
     * 解析 APK 文件
     * @param is 输入流
     * @return Map<String,Map<String,Object>>
     */
    public static Map<String,Map<String,Object>> analyzeApk(InputStream is) {
        Map<String,Map<String,Object>> resultMap = new HashMap<String,Map<String,Object>>();
        try {
            ZipInputStream zipIs = new ZipInputStream(is);
            zipIs.getNextEntry();
            AXmlResourceParser parser = new AXmlResourceParser();
            parser.open(zipIs);
            boolean flag = true;
            while(flag) {
                int type = parser.next();
                if (type == XmlPullParser.START_TAG) {
                    int count = parser.getAttributeCount();
                    String action = parser.getName().toUpperCase();
                    if(action.equals("MANIFEST") || action.equals("APPLICATION")) {
                        Map<String,Object> tempMap = new HashMap<String,Object>();
                        for (int i = 0; i < count; i++) {
                            String name = parser.getAttributeName(i);
                            String value = parser.getAttributeValue(i);
                            value = (value == null) ? "" : value;
                            tempMap.put(name, value);
                        }
                        resultMap.put(action, tempMap);
                    } else {
                        Map<String,Object> manifest = resultMap.get("MANIFEST");
                        Map<String,Object> application = resultMap.get("APPLICATION");
                        if(manifest != null && application != null) {
                            flag = false;
                        }
                        continue;
                    }
                }
            }
            zipIs.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resultMap;
    }
    /**
     * 解析 IPA 文件
     * @param is 输入流
     * @return Map<String, Object>
     */
    public static Map<String, Object> analyzeIpa(InputStream is) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            ZipInputStream zipIs = new ZipInputStream(is);
            ZipEntry ze;
            InputStream infoIs = null;
            while ((ze = zipIs.getNextEntry()) != null) {
                if (!ze.isDirectory()) {
                    String name = ze.getName();
                    // 读取 info.plist 文件
                    // FIXME: 包里可能会有多个 info.plist 文件！！！
                    if (name.contains(".app/Info.plist")) {
                        ByteArrayOutputStream abos = new ByteArrayOutputStream();
                        int chunk = 0;
                        byte[] data = new byte[256];
                        while(-1 != (chunk = zipIs.read(data))) {
                            abos.write(data, 0, chunk);
                        }
                        infoIs = new ByteArrayInputStream(abos.toByteArray());
                        break;
                    }
                }
            }
            NSDictionary rootDict = (NSDictionary) PropertyListParser.parse(infoIs);
            String[] keyArray = rootDict.allKeys();
            for (String key : keyArray) {
                NSObject value = rootDict.objectForKey(key);
                if (key.equals("CFBundleSignature")) {
                    continue;
                }
                if (value.getClass().equals(NSString.class) || value.getClass().equals(NSNumber.class)) {
                    resultMap.put(key, value.toString());
                }
            }
//            String endpoint = "http://oss-cn-beijing.aliyuncs.com";
//            String host = "oss-cn-beijing.aliyuncs.com";
//            String accessKeyId = "LTAIKtPsVetVcT3P";
//            String accessKeySecret = "n6rZrTenjRavE4emK8Ow5EnEtnOIbB";
//            String bucketName = "ceshixiazai";
//            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
//            ossClient.putObject(bucketName,"2.3.2/CRM_YUN.ipa",is);
//            ossClient.shutdown();
            if(null!= zipIs ){
                zipIs.close();
                is.close();
            }
        } catch (Exception e) {
            resultMap.put("error", e.getStackTrace());
        }
        return resultMap;
    }
}
